package com.mike.fragmentdemo3.Fragment.Service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.mike.fragmentdemo3.Fragment.Bean.MusicBean;
import com.mike.fragmentdemo3.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private Timer timer;//时钟对象
    private List<MusicBean> mediaPlayerList;//多媒体对象
    private MediaPlayer mediaPlayer; //音乐播放器类
    private int i = 0;//歌曲列表的索引
    private float mCurrentPlaybackSpeed = 1.0f; // 默认播放速度为1.0
    private static final String TAG = "MusicService"; //打印日志
    private OnPlayInfoListener mOnPlayInfoListener; //音乐信息更改监听器
    public MusicService() {

    }
    // 定义播放模式枚举
    public enum PlayMode {
        SINGLE_CYCLE, // 单曲循环
        SEQUENTIAL,   // 顺序播放
        RANDOM        // 随机播放
    }
    // 添加播放模式成员变量
    private PlayMode currentPlayMode = PlayMode.SEQUENTIAL;

    // 切换播放模式的方法
    public void setPlayMode(PlayMode mode) {
        currentPlayMode = mode;
    }

    public interface OnPlayInfoListener {
        void onPlayInfo(Bundle bundle); //通过Bundle传递参数
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl(); //绑定服务的时候，把音乐控制类实例化
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //实例化多媒体对象
        mediaPlayer = new MediaPlayer();
        mediaPlayerList = new ArrayList<>();
        MusicBean musicBean1 = new MusicBean("1Falling Down", "队长", R.raw.music1, R.drawable.a);
        MusicBean musicBean2 = new MusicBean("2五彩的纯白", "李尧音Dirbig大民民", R.raw.music, R.drawable.b);
        MusicBean musicBean3 = new MusicBean("3独家编剧", "ConeG", R.raw.music2, R.drawable.c);
        MusicBean musicBean4 = new MusicBean("4月亮说", "Mimmi", R.raw.music3, R.drawable.d);
        MusicBean musicBean5 = new MusicBean("5晚风夕阳 你", "周周", R.raw.music4, R.drawable.e);
        mediaPlayerList.add(musicBean1);
        mediaPlayerList.add(musicBean2);
        mediaPlayerList.add(musicBean3);
        mediaPlayerList.add(musicBean4);
        mediaPlayerList.add(musicBean5);
        add();
    }
    private void add(){
        File file = new File("F:\\NewAndroid\\AmartHomeApp1123zmh\\app\\src\\main\\res\\raw");
        System.out.println("++++----"+file.list());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

    public class MusicControl extends Binder {

        public void registerPlayInfoChange(OnPlayInfoListener listener) {
            mOnPlayInfoListener = listener;
        }
        //音乐播放
        public void play() {
            mediaPlayer.reset();
            mediaPlayer = MediaPlayer.create(getApplicationContext(), mediaPlayerList.get(i).getSourceId());
            mediaPlayer.start();
            addTimer();
            mediaPlayer.setOnCompletionListener(
                    new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            int currentIndex = getCurrentIndex();
                            int newIndex ;
                            switch (currentPlayMode) {
                                case SINGLE_CYCLE:
                                    newIndex = currentIndex; // 单曲循环，索引不变
                                    break;
                                case SEQUENTIAL:
                                    newIndex = (currentIndex + 1) % getSongCount(); // 顺序播放，循环回到第一首
                                    break;
                                case RANDOM:
                                    newIndex = (int) (Math.random() * getSongCount()); // 随机播放，生成随机索引
                                    break;
                                default:
                                    newIndex = currentIndex; // 默认顺序播放
                            }

                            changeSong(newIndex); // 切换歌曲
                        }
                    });
        }
        //音乐暂停
        public void pause() {
            mediaPlayer.pause();
        }
        //继续播放
        public void resume() {
            mediaPlayer.start();//播放，不会重置
        }
        //释放资源
        public void stop() {
            mediaPlayer.stop();
            mediaPlayer.release();
            try {
                timer.cancel();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //进度条显示
        public void seekTo(int ms) {
            mediaPlayer.seekTo(ms);
        }

        // 获取当前播放索引
        public int getCurrentIndex() {
            return i; // 返回当前播放的索引
        }

        // 获取歌曲总数
        public int getSongCount() {
            return mediaPlayerList.size(); // 返回mediaPlayerList的大小
        }

        //改变播放倍速
        public void ChangePlaySpeed(float speed){
            PlaybackParams params = mediaPlayer.getPlaybackParams();
            params.setSpeed(speed); // 设置播放速度
            mediaPlayer.setPlaybackParams(params);
            mediaPlayer.start(); // 可能需要调用start()来确保立即应用速度变化，取决于你的具体需求
            // 更新当前保存的播放速度
            mCurrentPlaybackSpeed = speed;
        }

        // 获取当前播放模式
        public PlayMode getPlayMode() {
            return currentPlayMode;
        }

        public void setPlayMode(int playMode) {
            // 根据传入的playMode更新currentPlayMode
            // 注意：这里我使用了int而不是PlayMode枚举，因为枚举在IPC中可能不方便传递
            // 如果你坚持使用枚举，你可能需要通过其他方式（如序列化）来传递它
            switch (playMode) {
                case 0:
                    currentPlayMode = PlayMode.SEQUENTIAL;
                    break;
                case 1:
                    currentPlayMode = PlayMode.SINGLE_CYCLE;
                    break;
                case 2:
                    currentPlayMode = PlayMode.RANDOM;
                    break;
                default:
                    currentPlayMode = PlayMode.SEQUENTIAL; // 默认顺序播放
            }
        }
        public Bundle getFirstSongInfo() {
            int duration = 0;
            if (mediaPlayerList != null && !mediaPlayerList.isEmpty()) {
                MusicBean firstSong = mediaPlayerList.get(0);
                if (mediaPlayerList != null && !mediaPlayerList.isEmpty()) {
                    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), mediaPlayerList.get(0).getSourceId());
                    if (mp != null) {
                        duration = mp.getDuration();
                        mp.release();
                    }
                }
                Bundle bundle = new Bundle();
                bundle.putString("name", firstSong.getName());
                bundle.putString("singer", firstSong.getSinger());
                bundle.putInt("image", firstSong.getImage());
                bundle.putInt("duration",duration); // 你需要实现这个方法来获取第一首歌的时长
                return bundle;
            }
            return null;
        }
        // 切换歌曲
        public void changeSong(int newIndex) {
            // 如果新索引超出范围，则不进行切换
            if (newIndex < 0 || newIndex >= mediaPlayerList.size()) {
                return;
            }
            // 在随机播放模式下，确保新索引不等于当前索引
            if (currentPlayMode == PlayMode.RANDOM && newIndex == i) {
                do {
                    newIndex = (int) (Math.random() * getSongCount());
                } while (newIndex == i);
            }
            // 停止当前播放的音乐
            if (mediaPlayerList.get(i) != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release(); // 释放当前MediaPlayer资源
            i = newIndex; // 更新索引

            try {
                mediaPlayer = MediaPlayer.create(getApplicationContext(), getMusicResourceId(newIndex));
                if (mediaPlayer != null) {
                    play(); // 调用play方法来准备和开始播放新歌曲

                    // 设置新歌曲的播放速度为当前保存的播放速度
                    PlaybackParams params = mediaPlayer.getPlaybackParams();
                    params.setSpeed(mCurrentPlaybackSpeed);
                    mediaPlayer.setPlaybackParams(params);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //增加计时器
        public void addTimer() {
            if (timer != null) {
                timer.cancel(); // 取消旧的计时器（如果有的话）
                timer = null;
            }
            if (timer == null) {
                timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        if (mediaPlayerList != null && i >= 0 && i < mediaPlayerList.size() &&
                                mediaPlayerList.get(i) != null && mediaPlayer != null) {
                            try {
                                if (mOnPlayInfoListener != null) {
                                    int duration = mediaPlayer.getDuration(); // 获取歌曲总时长
                                    int currentPos = mediaPlayer.getCurrentPosition();// 获取当前播放进度
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("duration", duration);
                                    bundle.putInt("currentPosition", currentPos);
                                    bundle.putString("name", mediaPlayerList.get(i).getName());
                                    bundle.putString("singer", mediaPlayerList.get(i).getSinger());
                                    bundle.putInt("image", mediaPlayerList.get(i).getImage());
                                    mOnPlayInfoListener.onPlayInfo(bundle);
                                }
                            } catch (IllegalStateException e) {
                                // 处理 MediaPlayer 状态异常
                                Log.e("MusicService", "MediaPlayer in invalid state when trying to get current position", e);
                                // 在这里，你可能需要做一些恢复操作，比如重新准备 MediaPlayer（注意线程问题）
                                // 或者简单地记录错误并忽略这次更新
                            }
                        }
                    }
                };
                //开始计时任务后的5毫秒，第一次执行task任务，以后每500毫秒执行一次
                timer.schedule(task, 5, 10);
            }
        }

        // 辅助方法，根据索引获取音乐资源的ID
        private int getMusicResourceId(int index) {
            switch (index) {
                case 0:
                    return R.raw.music1;
                case 1:
                    return R.raw.music;
                case 2:
                    return R.raw.music2;
                case 3:
                    return R.raw.music3;
                case 4:
                    return R.raw.music4;
                default:
                    throw new IllegalArgumentException("Invalid index: " + index);
            }
        }
    }

}


